Fork me on GitHub

110. Balanced Binary Tree

欢迎fork and star:Nowcoder-Repository-github

110. Balanced Binary Tree

题目

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 

解析

class Solution_110 {
public:
	int getHeight(TreeNode* root)
	{
	     if (!root)
	     {
			 return 0;
	     }

		 int left = getHeight(root->left);
		 int right = getHeight(root->right);

		 return (left > right) ? (left + 1):(right + 1);
	}

	bool isBalanced(TreeNode *root) {
		if (!root)
		{
			return true;
		}
		// 不应该用<=1,return true,这样就提前返回了 
		//if (abs(getHeight(root->left) - getHeight(root->right)) > 1) {
		//	return false;
		//}
		//递归:自顶向下
		return  abs(getHeight(root->left) - getHeight(root->right) <= 1) && isBalanced(root->left) && isBalanced(root->right);
	}

	// method2
	bool isBalanced1(TreeNode *root) {
		int depth = 0;
		return isBalanced_helper(root, depth);
	}
	bool isBalanced_helper(TreeNode *root, int &depth) {
		if (root == NULL){
			depth = 0;
			return true;
		}
		int left, right;
		if (isBalanced_helper(root->left, left) && isBalanced_helper(root->right, right)){
			if (abs(left - right) <= 1){
				depth = 1 + max(left, right);
				return true;
			}
		}
		return false;
	}
};



题目来源

posted @ 2018-01-08 10:56  ranjiewen  阅读(265)  评论(0编辑  收藏  举报